package in.muton.edushare.pages.user;

import in.muton.edushare.helper.TinyMCEHelper;
import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.pages.common.EdusharePanel;
import in.muton.edushare.panels.MonthYearInputBox;
import in.muton.edushare.validators.formvalidators.DateComparisonValidator;
import in.muton.edushare.wicket.models.CayenneModel;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.dao.ProfessionalDetailsDAO;
import com.edushare.common.util.DateTimeUtil;
import com.edushare.common.vo.ProfessionalDetails;
import com.edushare.common.vo.Users;

public class EditProfileExpPanel extends EdusharePanel {

	private boolean isEditMode = false;
	private int profileType;
	private IModel<ProfessionalDetails> proDetailModel;
	
	public EditProfileExpPanel(String id, IModel<Users> model, EduShareBasePage page, int professionalDetailType) {
		super(id, model, page);
		this.profileType  = professionalDetailType;
		
		proDetailModel = new CayenneModel<ProfessionalDetails>(new ProfessionalDetails());
		WebMarkupContainer formCont = new WebMarkupContainer("proformdiv"){
			@Override
			protected void onBeforeRender() {
				if(isEditMode){
					this.add(new AttributeAppender("style", true, new Model<String>("display:block"), ";"));
				}else{
					this.add(new AttributeAppender("style", true, new Model<String>("display:none"), ";"));
				}
				super.onBeforeRender();
			}
		};
		formCont.setOutputMarkupId(true);
		formCont.setMarkupId("proformdiv");
		add(formCont);
		
		Form<Void> form = new Form<Void>("proform"){
			
			private static final long serialVersionUID = -6138152523944567134L;
			
			@Override
			protected void onError() {
				setError("Error: Inappropriate input, please see if entered values are correct?");
				isEditMode = true;//let the dialogue box open
			};

			@Override
			protected void onSubmit() {
				if(proDetailModel.getObject().getDescription()!=null && proDetailModel.getObject().getDescription().length() > ApplicationConstants.MAX_DESC_SIZE){
					setError("Error: Summary / Description is too long.");
					isEditMode = true;//let the dialogue box open
					return;
				}else if(proDetailModel.getObject().getOrgName()!=null && proDetailModel.getObject().getOrgName().length() > ApplicationConstants.MAX_TEXT_FIELD_SIZE){
					if(EditProfileExpPanel.this.profileType == ProfessionalDetails.PRO_DETAIL_TYPE_POSITION){
						setError("Error: Organization name is too long.");
					}else{
						setError("Error: University/Institute name is too long.");
					}
					return;
				}else if(proDetailModel.getObject().getOrgName()==null || proDetailModel.getObject().getOrgName().trim().length() < 1){
					if(EditProfileExpPanel.this.profileType == ProfessionalDetails.PRO_DETAIL_TYPE_POSITION){
						setError("Error: Organization name is required");
					}else{
						setError("Error: University/Institute name is required");
					}
					return;
				}else if(proDetailModel.getObject().getPositionTitle()!=null && proDetailModel.getObject().getPositionTitle().length() > ApplicationConstants.MAX_TEXT_FIELD_SIZE){
					if(EditProfileExpPanel.this.profileType == ProfessionalDetails.PRO_DETAIL_TYPE_POSITION){
						setError("Error: Position Name / Title is too long.");
					}else{
						setError("Error: Degree name is too long.");
					}
					isEditMode = true;//let the dialogue box open
					return;
				}else if(proDetailModel.getObject().getPositionTitle()==null || proDetailModel.getObject().getPositionTitle().trim().length() < 1){
					if(EditProfileExpPanel.this.profileType == ProfessionalDetails.PRO_DETAIL_TYPE_POSITION){
						setError("Error: Position Name / Title is required");
					}else{
						setError("Error: Degree name is required");
					}
					isEditMode = true;//let the dialogue box open
					return;
				}else if(proDetailModel.getObject().getSpecialization()!=null && proDetailModel.getObject().getSpecialization().length() > ApplicationConstants.MAX_TEXT_FIELD_SIZE){
					setError("Error: specialization is too long.");
					isEditMode = true;//let the dialogue box open
					return;
				}
				
				proDetailModel.getObject().setProDetailType(EditProfileExpPanel.this.profileType);
				if(proDetailModel.getObject().getIsCurrent()){
					proDetailModel.getObject().setToDate(null);
				}
				new ProfessionalDetailsDAO(getORMInterface()).saveOrUpdate(proDetailModel.getObject(), getLoggedInUser());
				getORMInterface().commitAllChanges();
				//reset the form
				setProDetail(new ProfessionalDetails());
				isEditMode = false;
				clearError();
			}
		};
		
		formCont.add(form);
		loadHeading(form);
		form.add(new TextField<String>("title", new PropertyModel<String>(this, "proDetail.positionTitle")));
		WebMarkupContainer splInCont = new WebMarkupContainer("splInCont");
		form.add(splInCont);
		TextField<String> splIn = new TextField<String>("splIn", new PropertyModel<String>(this, "proDetail.specialization"));
		splInCont.add(splIn);
		if(this.profileType != ProfessionalDetails.PRO_DETAIL_TYPE_DEGREE){
			splInCont.setVisible(false);
		}
		
		form.add(new TextField<String>("org", new PropertyModel<String>(this, "proDetail.orgName")));
		TextArea<String> dec = new TextArea<String>("desc", new PropertyModel<String>(this, "proDetail.description"));
		dec.add(TinyMCEHelper.getDefaultTinyMCEBehavior());
		form.add(dec);
		
		final MonthYearInputBox orgFromDate = new MonthYearInputBox("dateFrom",new PropertyModel<Date>(this, "proDetail.FromDate"));
		orgFromDate.setRequired(true);
		form.add(orgFromDate);
		final MonthYearInputBox toDate = new MonthYearInputBox("dateTo",new PropertyModel<Date>(this, "proDetail.toDate"));
		toDate.setOutputMarkupId(true);
		toDate.setMarkupId("dateTo");
		form.add(toDate);
		DateComparisonValidator dateValidator = new DateComparisonValidator(orgFromDate, toDate);
		form.add(dateValidator);
		CheckBox isCurrent = new CheckBox("isCurrent", new PropertyModel<Boolean>(this, "proDetail.isCurrent"));
		isCurrent.setOutputMarkupId(true);
		isCurrent.setMarkupId("isCurrent");
		form.add(isCurrent);
		
		
		ListView<ProfessionalDetails> proDetailLV = 
			new ListView<ProfessionalDetails>("prodetailList", new PropertyModel<List<ProfessionalDetails>>(EditProfileExpPanel.this, "proList")){

				private static final long serialVersionUID = -8177331694301650933L;

				@Override
				protected void populateItem(final ListItem<ProfessionalDetails> item) {
					WebMarkupContainer wmc = new WebMarkupContainer("proDetCont");
					item.add(wmc);
					wmc.add(new Label("positionTitle", new PropertyModel<String>(item.getModel(), "positionTitle")));
					wmc.add(new Label("orgName", new PropertyModel<String>(item.getModel(), "orgName")));
					wmc.add(new Label("fromDate", new Model<String>(DateTimeUtil.formatDate(item.getModelObject().getFromDate()))));
					if(item.getModelObject().getIsCurrent()){
						wmc.add(new Label("toDate", "Present"));
					}else{
						wmc.add(new Label("toDate", new Model<String>(DateTimeUtil.formatDate(item.getModelObject().getToDate()))));
					}
					
					wmc.add(new Label("description", new PropertyModel<String>(item.getModel(), "description")).setEscapeModelStrings(false));
					if((item.getIndex()+1)%2==0){
						wmc.add(new AttributeAppender("style", true, new Model<String>("background-color:#EEF"), ";"));
					}else{
						wmc.add(new AttributeAppender("style", true, new Model<String>("background-color:#CCC"), ";"));
					}
					wmc.add(new Link<Void>("edit"){

						@Override
						public void onClick() {
							EditProfileExpPanel.this.proDetailModel = item.getModel();
							isEditMode = true;
						}
						
					});
					
					wmc.add(new Link<Void>("delete"){

						@Override
						public void onClick() {
							new ProfessionalDetailsDAO(getORMInterface()).delete(item.getModelObject());
							//reset the form if delete is clicked, mat be the person was editing this when he decides to delete this.
							isEditMode=false;
							EditProfileExpPanel.this.setProDetail(new ProfessionalDetails());
						}
						
					});
					
				}
			
		};
		
		add(proDetailLV);
	}
	
	private void loadHeading(Form form) {
		
		boolean showExp = true;
		if(this.profileType == ProfessionalDetails.PRO_DETAIL_TYPE_POSITION){
			showExp = true;
		}else{
			showExp = false;
		}
		
		add(new WebMarkupContainer("addMore1").setVisible(showExp));
		add(new WebMarkupContainer("addMore2").setVisible(!showExp));
		
		List<WebMarkupContainer> expHeaders = new ArrayList<WebMarkupContainer>();
		expHeaders.add(new WebMarkupContainer("legend1"));
		expHeaders.add(new WebMarkupContainer("ttlph1"));
		expHeaders.add(new WebMarkupContainer("orgph1"));
		expHeaders.add(new WebMarkupContainer("currentph1"));
		expHeaders.add(new WebMarkupContainer("summ1"));
		
		for(WebMarkupContainer wmc:expHeaders){
			form.add(wmc.setVisible(showExp));
		}
		
		List<WebMarkupContainer> eduHeaders = new ArrayList<WebMarkupContainer>();
		eduHeaders.add(new WebMarkupContainer("legend2"));
		eduHeaders.add(new WebMarkupContainer("ttlph2"));
		eduHeaders.add(new WebMarkupContainer("orgph2"));
		eduHeaders.add(new WebMarkupContainer("currentph2"));
		eduHeaders.add(new WebMarkupContainer("summ2"));
		
		for(WebMarkupContainer wmc:eduHeaders){
			form.add(wmc.setVisible(!showExp));
		}
		
	}

	public List<ProfessionalDetails> getProList(){
		if(this.profileType == ProfessionalDetails.PRO_DETAIL_TYPE_POSITION){
			return new ProfessionalDetailsDAO(getORMInterface()).getPositions(getLoggedInUser());
		}else{
			return new ProfessionalDetailsDAO(getORMInterface()).getdegrees(getLoggedInUser());
		}
	}

	public void setProDetail(ProfessionalDetails proDetailModel) {
		this.proDetailModel = new CayenneModel<ProfessionalDetails>(proDetailModel);
	}

	public ProfessionalDetails getProDetail() {
		return proDetailModel.getObject();
	}

}
